//cookie获取和存储方法
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
//解析url参数  
function parseUrl() {
    let keys = location.search.substr(1).split("&");
    let json = {};
    keys.forEach((e, i) => {
        let k = e.split("=")[0];
        let v = decodeURIComponent(e.split("=")[1]);
        json[k] = v;
    })
    return json;
}
//判断登录是否成功
let login = isLogin();
let id;
$(document).ready(function () {
    if (login == undefined) {
        $("#loginSuccess").hide();
    } else {
        $.ajax({
            type: "get",
            url: `http://localhost:3301/user?phone=${login}`,
            async: false,
            success: function (e) {
                id = e[0].id;
                $("#login_name").html(e[0].nickname);
            }
        })
        $("#goLogin").hide();
        //登录成功后需要获取本地的购物车，添加到该用户数据库内
        if (getCookie("cart") != "") {
            let cartdb = JSON.parse(getCookie("cart"));
            cartdb.forEach((e, i) => {
                e.user_id = id;
                addOrPutCart(e);
            })
            setCookie("cart", "", 0);
        }
    }
    $("#signout").click(function () {
        if (confirm("确定要注销吗？")) {
            if (window.sessionStorage.getItem("login") != null && window.sessionStorage.getItem("login") != "") {
                login = window.sessionStorage.removeItem("login");
            } else if (getCookie("login") != "") {
                login = setCookie("login", null, -1);
            }
            location.reload();
        }
    })
})
//商品分类加载完成后添加数据
$(".all-sort-list2").ready(function () {
    $.ajax({
        type: "get",
        async: false,
        url: "http://localhost:3301/category?_order=sort&_sort=desc",
        success: function (data) {
            data.forEach((e, i) => {
                if (e.pid == 0) {
                    let item = $(`<div class="item"><h3><a href="">${e.cate_name}</a></h3><div class="item-list clearfix" style="display: none;"><div class="subitem"></div></div></div>`);
                    let item_list = item.find(".subitem");
                    data.forEach((e2, i2) => {
                        if (e2.pid == e.id) {
                            let dl = $(`<dl class='fore1'></dl>`);
                            let dt = $(`<dt><a href="javascript:;">${e2.cate_name}</a></dt>`);
                            let dd = $(`<dd></dd>`);
                            data.forEach((e3, i3) => {
                                if (e3.pid == e2.id) {
                                    let em = $(`<em><a href="#">${e3.cate_name}</a></em>`);
                                    dd.append(em);
                                }
                            });
                            dl.append(dt);
                            dl.append(dd);
                            item_list.append(dl);
                        }
                    })
                    $(".all-sort-list2").append(item);
                }
            })
        }
    });
    $(".all-sort-list2 .item").mouseover(function () {
        $(this).addClass("hover");
        $(this).find("div").show();
    })
    $(".all-sort-list2 .item").mouseout(function () {
        $(".all-sort-list2 .item").find("div").hide();
        $(".all-sort-list2 .item").removeClass("hover");
    })
    $(".toolbar-tabs .toolbar-tab").hover(function () {
        $(this).addClass("tbar-tab-selected");
        $(this).find("em").addClass("tbar-tab-hover");
        $(this).find("em").html($(this).attr("data"));
    }, function () {
        $(".toolbar-tab").removeClass("tbar-tab-selected");
        $(this).find("em").removeClass("tbar-tab-hover");
    })
    $(".toolbar-footer .toolbar-tab").hover(function () {
        $(this).addClass("tbar-tab-selected");
        $(this).find("em").addClass("tbar-tab-footer-hover");
        $(this).find("em").html($(this).attr("data"));
    }, function () {
        $(".toolbar-tab").removeClass("tbar-tab-selected");
        $(this).find("em").removeClass("tbar-tab-footer-hover");
    })
    $(".all-sort,.sort").hover(function () {
        $(".sort").show();
    }, function () {
        $(".sort").hide();
    })

})
//选中显示对应的模块
function tabItemClick(e) {
    if ($(".toolbar-wrap").hasClass(".toolbar-open")) {
        panel_close(e);
    } else {
        panel_open(e);
    }
}
function panel_close(e) {
    $(`.toolbar-tab`).find("em").show();
    $(`.toolbar-panel`).css({ "visibility": "hidden", "z-index": "-1" });
    $(".toolbar-wrap").removeClass("toolbar-open");
}
function panel_open(e) {
    if (!$(".tbar-tab-" + e).hasClass("tbar-tab-click-selected")) {
        $(".toolbar-tab").removeClass("tbar-tab-click-selected");
        panel_close(e);
        $(".toolbar-wrap").addClass("toolbar-open");
        $(`[tag=${e}]`).addClass("tbar-tab-click-selected");
        $(`[tag=${e}]`).find("em").hide();
        $(`.tbar-panel-${e}`).css({ "visibility": "visible", "z-index": "1" });
    } else {
        $(".tbar-tab-" + e).removeClass("tbar-tab-click-selected");
        panel_close(e);
    }
}
//判断是否登录
function isLogin() {
    let login;
    if (window.sessionStorage.getItem("login") != null && window.sessionStorage.getItem("login") != "") {
        login = window.sessionStorage.getItem("login");
    } else if (getCookie("login") != "") {
        login = getCookie("login");
    }
    return login;
}
$(".tbar-panel-main").ready(function () {
    let login = isLogin();
    let count = 0;
    let total_price = 0;
    let carts = [];
    let temp = $("#tbar-cart-item-template").html();
    if (login != undefined) {
        //登录查询该用户的购物车
        let id;
        $.ajax({
            url: "http://localhost:3301/user?phone=" + login,
            type: "get",
            async: false,
            success: function (data) {
                id = data[0].id;
            }
        })
        $.ajax({
            type: "get",
            url: "http://localhost:3301/cart?user_id=" + id,
            async: false,
            success: function (data) {
                carts = data;
            }
        })
    } else {
        //未登录查看本地存储的购物车信息
        $("#J-cart-tips").show();
        if (getCookie("cart") != "") {
            carts = JSON.parse(getCookie("cart"));
        }
    }
    carts.forEach((e, i) => {
        $.ajax({
            type: "get",
            url: "http://localhost:3301/goods?id=" + e.goods_id,
            async: false,
            success: function (d2) {
                let flag = true;
                let dd = d2[0];
                let name = dd.goods_name.split(" ")[0];
                let temp = $("#tbar-cart-item-template").html();
                temp = temp.replaceAll("{2}", dd.goods_logo);
                if (e.spec_goods_id != undefined) {
                    $.ajax({
                        type: "get",
                        url: "http://localhost:3301/spec_goods?id=" + e.spec_goods_id,
                        async: false,
                        success: function (spec_goods) {
                            flag = false;
                            let spec = spec_goods[0];
                            temp = temp.replaceAll("{3}", spec.price);
                            total_price += parseInt(spec.price) * parseInt(e.number);
                            name += " " + spec.value_names;
                        }
                    })
                }
                temp = temp.replaceAll("{1}", name);
                if (flag) {
                    temp = temp.replaceAll("{3}", dd.goods_price);
                    total_price += parseInt(e.price) * parseInt(e.number);
                }
                temp = temp.replaceAll("{4}", e.number);
                count += parseInt(e.number);
                $("#cart-list").append(temp);
            }
        })
    })
    $("#tab-sub-cart-count").html(count);
    $("#cart-number").html(count);
    $("#cart-sum").html(total_price + ".00￥");
})
function addOrPutCart(goods) {
    console.log(goods);
    $.ajax({
        type: "get",
        url: `http://localhost:3301/cart?user_id=${goods.user_id}&goods_id=${goods.goods_id}&spec_goods_id=${goods.spec_goods_id}`,
        async: false,
        success: function (data) {
            if (!$.isEmptyObject(data)) {
                data[0].number = parseInt(data[0].number) + goods.number;
                $.ajax({
                    type: "put",
                    url: `http://localhost:3301/cart/${data[0].id}`,
                    data: data[0],
                    async: false,
                    success: function (data) {
                        console.log(data);
                    }
                })
            } else {
                goods.create_time = new Date().getTime();
                $.ajax({
                    type: "post",
                    url: `http://localhost:3301/cart`,
                    data: goods,
                    async: false,
                    success: function (data) {
                        console.log(data);
                    }
                })
            }
        }
    })
}
let address = {};
try {
    address = ChineseDistricts;
} catch (error) {

}
$(document).ready(function () {

    //新增地址框显示
    //加入地址信息
    let province = $("#province");
    for (let e in address[86]) {
        let op = $(`<option value="${e}">${address[86][e]}</option>`);
        province.append(op);
    }
    $("#province").change(function () {
        cityShow();
    })
    cityShow();
    district();
    $("#city").change(function () {
        district();
    })
    $("#sub_address").click(function () {
        if ($("#myModalLabel").html() == "添加收货地址") {
            let consignee = $(".form-horizontal [name=consignee]").val();
            let province = parseInt($(".form-horizontal [name=province]").val());
            let city = parseInt($(".form-horizontal [name=city]").val());
            let district = parseInt($(".form-horizontal [name=district]").val());
            let adr = $(".form-horizontal [name=address]").val();
            let phone = $(".form-horizontal [name=phone]").val();
            let is_default = $(".form-horizontal [name=is_default]").prop("checked");
            let area = address[86][province] + "" + address[province][city] + "" + address[city][district];
            let create_time = new Date().getTime();
            let data = {
                user_id: id, consignee: consignee,
                phone: phone, province: province, city: city,
                district: district, area: area, address: adr, is_default: is_default, create_time: create_time
            };
            addAddress(data);
        } else if ($("#myModalLabel").html() == "编辑收货地址") {
            let aid = parseInt($(".form-horizontal [name=id]").val());
            let consignee = $(".form-horizontal [name=consignee]").val();
            let province = parseInt($(".form-horizontal [name=province]").val());
            let city = parseInt($(".form-horizontal [name=city]").val());
            let district = parseInt($(".form-horizontal [name=district]").val());
            let adr = $(".form-horizontal [name=address]").val();
            let phone = $(".form-horizontal [name=phone]").val();
            let is_default = $(".form-horizontal [name=is_default]").prop("checked");
            let area = address[86][province] + "" + address[province][city] + "" + address[city][district];
            let create_time = new Date().getTime();
            let data = {
                id: aid, user_id: id, consignee: consignee,
                phone: phone, province: province, city: city,
                district: district, area: area, address: adr, is_default: is_default, create_time: create_time
            };
            put_addr(data);
        }
        close_box();
    })
})
//显示
function show_box() {
    $(".sui-modal-backdrop").show();
    $(".sui-modal-backdrop").animate({ opacity: 0.5 }, 400);
    $(".sui-modal").show();
    $(".sui-modal").animate({ 'top': '120px', opacity: 1 }, 400);
    $(".form-horizontal")[0].reset();
}
//关闭
function close_box() {
    $(".sui-modal").animate({ 'top': '-350px', opacity: 0.5 }, 400, function () {
        $(".sui-modal-backdrop").animate({ opacity: 0 }, 400, function () {
            $(".sui-modal-backdrop").hide();
        });
    });
    $(".form-horizontal")[0].reset();
}
//添加地址方法
function addAddress(e) {
    //判断选中默认地址
    if (e.is_default) {
        //修改其他的地址状态
        $.ajax({
            type: "get",
            url: `http://localhost:3301/address?user_id=${e.user_id}&is_default=1`,
            async: false,
            success: function (d) {
                console.log(d);
                for (let i = 0; i < d.length; i++) {
                    d[i].is_default = 0;
                    $.ajax({
                        type: "put",
                        url: `http://localhost:3301/address/${d[i].id}`,
                        async: false,
                        data: d[i],
                        success: function (d) {
                            console.log("修改默认地址成功");
                        }
                    })
                }
            }
        })
    }
    //添加新的地址
    $.ajax({
        type: "post",
        url: "http://localhost:3301/address",
        async: false,
        data: {
            "user_id": e.user_id, "consignee": e.consignee,
            "phone": e.phone, "province": e.province, "city": e.city,
            "district": e.district, "area": e.area, "address": e.address, "is_default": e.is_default ? 1 : 0, "create_time": e.create_time
        },
        success: function (e) {
            console.log("地址添加成功");
        }
    })
}
function put_address(id, uid) {
    //消除其他的默认地址
    $.ajax({
        type: "get",
        url: `http://localhost:3301/address?user_id=${uid}&is_default=1`,
        async: false,
        success: function (d) {
            for (let i = 0; i < d.length; i++) {
                d[i].is_default = 0;
                $.ajax({
                    type: "put",
                    url: `http://localhost:3301/address/${d[i].id}`,
                    async: false,
                    data: d[i],
                    success: function (d) {
                        console.log("解绑默认地址");
                    }
                })
            }
        }
    })
    //修改其他的地址状态
    $.ajax({
        type: "get",
        url: `http://localhost:3301/address?id=${id}`,
        async: false,
        success: function (d) {
            d[0].is_default = 1;
            $.ajax({
                type: "put",
                url: `http://localhost:3301/address/${d[0].id}`,
                async: false,
                data: d[0],
                success: function (d) {
                    console.log("修改默认地址成功");
                }
            })
        }
    })
}
//查询地址
function get_address(id) {
    let addr;
    $.ajax({
        type: "get",
        url: `http://localhost:3301/address?id=${id}`,
        async: false,
        success: function (d) {
            addr = d[0];
        }
    })
    return addr;
}
//获取所有的地址信息
function get_address_all(uid){
    let addr = [];
    $.ajax({
        type: "get",
        url: `http://localhost:3301/address?user_id=${uid}&_sort=is_default&_order=desc`,
        async: false,
        success: function (d) {
            d.forEach((e,i)=>{
                addr.push(e);
            })
        }
    })
    return addr;
}
//修改地址
function put_addr(e) {
    //消除其他的默认地址
    if (e.is_default) {
        $.ajax({
            type: "get",
            url: `http://localhost:3301/address?user_id=${e.user_id}&is_default=1`,
            async: false,
            success: function (d) {
                for (let i = 0; i < d.length; i++) {
                    d[i].is_default = 0;
                    $.ajax({
                        type: "put",
                        url: `http://localhost:3301/address/${d[i].id}`,
                        async: false,
                        data: d[i],
                        success: function (d) {
                            console.log("解绑默认地址");
                        }
                    })
                }
            }
        })
    }
    $.ajax({
        type: "get",
        url: "http://localhost:3301/address?id=" + e.id,
        async: false,
        success: function (data) {
            e.is_default = e.is_default ? 1 : 0;
            $.ajax({
                type: "put",
                url: "http://localhost:3301/address/" + e.id,
                async: false,
                data: {
                    "user_id": e.user_id,
                    "consignee": e.consignee,
                    "phone": e.phone,
                    "province": e.province,
                    "city": e.city,
                    "district": e.district,
                    "area": e.area,
                    "address": e.address,
                    "is_default": e.is_default,
                    "update_time": new Date().getTime(),
                    "create_time": data[0].create_time,
                    "delete_time": data[0].delete_time
                },
                success: function (data) {
                    console.log("编辑成功");
                }
            })
        }
    })
}

function put_address_is_selected(rid) {
    //消除其他的默认地址
    $.ajax({
        type: "get",
        url: `http://localhost:3301/address?user_id=${id}&is_default=1`,
        async: false,
        success: function (d) {
            for (let i = 0; i < d.length; i++) {
                d[i].is_default = 0;
                $.ajax({
                    type: "put",
                    url: `http://localhost:3301/address/${d[i].id}`,
                    async: false,
                    data: d[i],
                    success: function (d) {
                        console.log("解绑默认地址");
                    }
                })
            }
        }
    })
    $.ajax({
        type: "get",
        url: "http://localhost:3301/address?id=" + rid,
        async: false,
        success: function (data) {
            data[0].is_default = 1;
            $.ajax({
                type: "put",
                url: "http://localhost:3301/address/" + rid,
                async: false,
                data: data[0],
                success: function (data) {
                    console.log("编辑成功");
                }
            })
        }
    })
}

function delete_address(rid) {
    $.ajax({
        type: "get",
        url: "http://localhost:3301/address?id=" + rid,
        async: false,
        success: function (data) {
            $.ajax({
                type: "delete",
                url: "http://localhost:3301/address/" + rid,
                async: false,
                success: function (data) {
                    console.log("删除成功");
                }
            })
        }
    })
}

function cityShow() {
    let p = $("#province").val();
    let city = $("#city");
    city.empty();
    for (let e in address) {
        if (parseInt(p) == parseInt(e)) {
            for (let a in address[e]) {
                city.append($(`<option value="${a}">${address[e][a]}</option>`));
            }
        }
    }
    district();
}

function district() {
    let c = $("#city").val();
    let p = $("#district");
    p.empty();
    for (let e in address) {
        if (parseInt(c) == parseInt(e)) {
            for (let a in address[e]) {
                p.append($(`<option value="${a}">${address[e][a]}</option>`));
            }
        }
    }
}
//获取选中的购物车商品
function get_selected_cart(uid) {
    let cart = [];
    let total_price = 0;
    let count = 0;
    $.ajax({
        type: "get",
        url: `http://localhost:3301/cart?user_id=${uid}&is_selected=1`,
        async: false,
        success: function (data) {
            cart = data;
            data.forEach((e, i) => {
                count++;
                $.ajax({
                    type: "get",
                    url: `http://localhost:3301/goods?id=${e.goods_id}`,
                    async: false,
                    success: function (goods) {
                        cart[i].goods_name = goods[0].goods_name;
                        cart[i].price = goods[0].goods_price;
                        cart[i].goods_logo = goods[0].goods_logo;
                    }
                })
                cart[i].value_names = "";
                if(e.spec_goods_id!=undefined){
                    $.ajax({
                        type: "get",
                        url: `http://localhost:3301/spec_goods?id=${e.spec_goods_id}`,
                        async: false,
                        success:function(spec){
                            cart[i].value_names = spec[0].value_names;
                            cart[i].price = spec[0].price;
                        }
                    })
                }
                total_price+=cart[i].price;
            })
            cart.total_price = total_price;
            cart.count = count;
        }
    })
    return cart;
}
//添加订单
function post_order(order,goods){
    let order_id ;
    //添加订单
    $.ajax({
        type:"post",
        url:"http://localhost:3301/order",
        async:false,
        data:{
        "order_sn": order.order_sn,
        "user_id": order.user_id,
        "order_status": 0,
        "consignee": order.consignee,
        "address": order.address,
        "phone": order.phone,
        "shipping_code": "yuantong",
        "shipping_name": "圆通",
        "shipping_sn": "",
        "pay_code": order.pay_code,
        "pay_name": order.pay_name,
        "invoice_title": "",
        "taxpayer": "",
        "invoice_desc": null,
        "user_note": "",
        "goods_price": 0,
        "shipping_price": 0,
        "coupon_price": 0,
        "order_amount": 0,
        "total_amount": order.total_amount,
        "create_time": order.create_time,
        "shipping_time": 0,
        "confirm_time": 0,
        "pay_time": 0,
        "update_time": null,
        "delete_time": null},
        success:function(order){
            order_id=order.id;
            console.log("订单添加成功");
        }
    })
    if(order_id!=undefined){
        goods.forEach((e,i)=>{
            $.ajax({
                type:"delete",
                url:"http://localhost:3301/cart/"+e.id,
                async:false,
                success:function(e){
                    console.log("购物车清除");
                }
            })
            $.ajax({
                type:"post",
                url:"http://localhost:3301/order_goods",
                async:false,
                data:{
                    "order_id": order_id,
                    "goods_id": e.goods_id,
                    "spec_goods_id": e.spec_goods_id,
                    "number": e.number,
                    "goods_name": e.goods_name,
                    "goods_logo": e.goods_logo,
                    "goods_price": 8000,
                    "spec_value_names": e.value_names,
                    "is_comment": 0,
                    "status": 0,
                    "create_time": new Date().getTime(),
                    "update_time": null,
                    "delete_time": null},
                    success:function(e){
                        console.log("商品添加到订单");
                    }
            })
        })
    }
    //跳到订单页面
    //本地存储一个cookie保存
    setCookie("order",String(order_id),0.25);
}
//根据电话号，获取登录用户id
function get_login(p){
    let id ;
    $.ajax({
        type:"get",
        url:"http://localhost:3301/user?phone="+p,
        async:false,
        success:function(e){
            id = e[0].id;
        }
    })
    return id;
}

function get_order(uid){
    let order = [];
    $.ajax({
        type:"get",
        url:"http://localhost:3301/order?user_id="+uid,
        async:false,
        success:function(e){
            e.forEach((e,i)=>{
                order.push(e);
            })
        }
    })
    return order;
}

function get_order_goods(oid){
    let goods = [];
    $.ajax({
        type:"get",
        url:"http://localhost:3301/order_goods?order_id="+oid,
        async:false,
        success:function(e){
            e.forEach((e,i)=>{
                goods.push(e);
            })
        }
    })
    return goods;
}